package com.flute.haflute.tools;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flute.haflute.jobbox.common.CloudConstants;

/**
 * 过滤器并重定向到'index.jsp'
 * 
 * @author Jazz
 */
public class RootFilter implements Filter {
	private FilterConfig filterConfig = null;

	public void init(FilterConfig config) {
		this.filterConfig = config;
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		if (this.filterConfig == null) {
			return;
		}
		if (req instanceof HttpServletRequest) {
			HttpServletRequest httpRequest = (HttpServletRequest) req;
			String path = httpRequest.getRequestURI();
			if (path == null || path.equals(httpRequest.getContextPath())
					|| (path.equals(httpRequest.getContextPath() + "/"))) {
				String tgt = this.filterConfig
						.getInitParameter(CloudConstants.ROOT_FILTER_STR);
				((HttpServletResponse) res)
						.sendRedirect((tgt == null) ? httpRequest
								.getContextPath() + "/index.jsp" : httpRequest
								.getContextPath() + tgt);
				return;
			}
		}
		chain.doFilter(req, res);
	}

	public void destroy() {
		this.filterConfig = null;
	}
}
